//
//  OPUser.m
//  OPFramework
//
//  Created by malcom on 7/12/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "OPUser.h"
#import "OPBoard.h"
#import "OPNSStringAdditions.h"
#import "OPCostants.h"

@implementation OPUser

@synthesize p_username;
@synthesize p_userid;

@synthesize p_avatar;
@synthesize p_lastPostDate;
@synthesize p_lastVisitDate;
@synthesize p_registrationDate;
@synthesize p_birthdayDate;
@synthesize p_signature;
@synthesize p_numberOfPosts;

@synthesize p_messenger_aim;
@synthesize p_messenger_msn;
@synthesize p_messenger_yim;
@synthesize p_messenger_jabber;
@synthesize p_messenger_icq;

@synthesize p_website;
@synthesize p_lang;
@synthesize p_userType;
@synthesize p_userRank;

- (id) initUserID:(NSNumber *) _uid fromBoard:(OPBoard *) _board  {
	OPUser *_user = [_board.obj_membersCache getUserMemberFromID: _uid];
	if (_user != nil) {
		[_user refreshCompleteProfile];
		return _user;
	} else {
		self = [super init];
		p_userid = [_uid intValue];
		_delegateBoard = [_board retain];
		
		// get profile
		[self refreshCompleteProfile];
		// add to cache
		[_delegateBoard.obj_membersCache addUserMember: self];
		return self;
	}
}

- (id) initWithUsername:(NSString *) _username andID:(NSNumber *) _id ofBoard:(OPBoard *) _board {
	self = [super init];
	if (self != nil) {
		p_username = [_username retain];
		p_userid = [_id intValue];
		_delegateBoard = [_board retain];
		
	}
	return self;
}

- (void) dealloc {
	[p_username release];
	
	[p_avatar release];
	[p_lastPostDate release];
	[p_lastVisitDate release];
	[p_registrationDate release];
	[p_birthdayDate release];
	[p_signature release];
	[p_numberOfPosts release];
	
	[p_messenger_aim release];
	[p_messenger_msn release];
	[p_messenger_yim release];
	[p_messenger_jabber release];
	[p_messenger_icq release];
	
	[p_website release];
	[p_lang release];
	[p_userType release];
	[p_userRank release];
	
	[super dealloc];
}


- (NSString *) description {
	return [NSString stringWithFormat: @"OPUser username: %@ (id: %d), number of posts %d, joined on %@ (avatar: %@)",p_username,p_userid,[p_numberOfPosts intValue], [p_registrationDate description],p_avatar];
}

- (id) initWithShortSummaryDataResponseFromPostLoad:(NSDictionary*) _data ofBoard:(OPBoard *) _board {
	self = [super init];
	if (self != nil) {
		// extract data from dictionary server by post info
		p_username = [[NSString alloc] initWithString: [_data objectForKey: @"post_username"]];
		p_userid = [[_data objectForKey: @"poster_id"] intValue];
		
		_delegateBoard = [_board retain];
		
		[self _loadShortSummaryFromData: _data];
	}
	return self;
}

- (void) _loadShortSummaryFromData:(NSDictionary *) _data {
	
	// setup avatar
	if ([_data objectForKey: @"poster_avatar"] != nil) {
		NSString *avatarPath = [[[_data objectForKey: @"poster_avatar"] returnImageURLFromHTMLImageTagOfBoard: _delegateBoard] retain];
		[p_avatar release];
		if (avatarPath != nil && [avatarPath length] > 0)
		//	p_avatar = [[NSImage alloc] initWithContentsOfURL: [NSURL URLWithString:avatarPath]];
			p_avatar = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: avatarPath]];
		[avatarPath release];
	}
	
	// user id
	p_userid = [[_data objectForKey:@"poster_id"] intValue];
	
	// registration date
	[p_registrationDate release];
	p_registrationDate = [[_data objectForKey: @"poster_joined"] retain];
	
	// posts
	[p_numberOfPosts release];
	p_numberOfPosts = [[_data objectForKey: @"poster_posts"] retain];
		
	// signature
	[p_signature release];
	p_signature = [[_data objectForKey: @"signature"] retain];
}

- (BOOL) refreshCompleteProfile {
	NSArray *_params = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt: 0],[NSNumber numberWithInt: p_userid],nil];
	XMLRPCResponse *userProfileResponse = [[_delegateBoard _executeRequestMethodNamed: @"user.getUserProfileFrom" 
																		   withParams: _params
																	   attachAuthData: NO] retain];

	BOOL err = NO;
	// it's not an error response, we can update data
	if (! (err = [self _checkErrorInRawResponseFromServer: userProfileResponse forMethod: @"user.getUserProfileFrom" ]) )
		[self _updateProfileWithData: (NSDictionary *)[userProfileResponse responseObject]];
	
	[_params release];
	[userProfileResponse release];
	return err;
}

- (BOOL) _isNumericResponseFromServerAnErrorCode:(NSNumber *) _code forMethod:(NSString *) method {
	_lastErrorCode = [_code intValue];
	switch ([_code intValue]) {
		case OFAPI_USERPROFILE_VIEW_NOTALLOWED:
		case OFAPI_USERPROFILE_VIEW_NOTALLOWEDANONYMOUS:
		case OFAPI_USERPROFILE_VIEW_NONEXISTINGMEMBER:
			return YES;
	}
	return NO;
}

- (void) _setAvatarImageFromFilename:(NSString *) _filename {
	// setup avatar
	NSString *avatarPath = [NSString stringWithFormat: @"%@/%@",_delegateBoard.obj_boardRootPath, _filename];
	[p_avatar release];
	p_avatar = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:avatarPath]];
}

- (void) _updateProfileWithData:(NSDictionary *) _data {
	
	[p_username release];
	p_username = [[_data objectForKey: OPUserProp_Username] retain];
	
	// setup avatar
	[self _setAvatarImageFromFilename: [_data objectForKey: OPUserProp_Avatar]];
	
	// last post time
	[p_lastPostDate release];
	p_lastPostDate = [[NSDate dateWithTimeIntervalSince1970:  [[_data objectForKey: OPUserProp_LastPostTime] longLongValue]] retain];
	
	// last visit time
	[p_lastVisitDate release];
	p_lastVisitDate = [[NSDate dateWithTimeIntervalSince1970:  [[_data objectForKey: OPUserProp_LastVisitTime] longLongValue]] retain];
				  
	// user reg date
	[p_registrationDate release];
	p_registrationDate = [[NSDate dateWithTimeIntervalSince1970:  [[_data objectForKey: OPUserProp_RegistrationDate] longLongValue]] retain];
				  
	// user birthday
	NSString *birthString = [_data objectForKey: OPUserProp_BirthdayDate];
	if (birthString != nil) {
		NSCalendarDate *birthday = [NSCalendarDate dateWithNaturalLanguageString: birthString];
		[p_birthdayDate release];
		if (birthday == nil || [[_data objectForKey: OPUserProp_Lang] isEqualToString: @"it"]) // italian??
			p_birthdayDate = [[NSCalendarDate dateWithString: birthString calendarFormat:@"%d-%m-%Y"] retain];
	}

	// posts
	[p_numberOfPosts release];
	p_numberOfPosts = [[_data objectForKey: OPUserProp_Posts] retain];
	
	// messengers
	[p_messenger_aim release]; p_messenger_aim = [[_data objectForKey: OPUserProp_MessengerAIM] retain];
	[p_messenger_msn release]; p_messenger_msn = [[_data objectForKey: OPUserProp_MessengerMSN] retain];
	[p_messenger_jabber release]; p_messenger_jabber = [[_data objectForKey: OPUserProp_MessengerJabber] retain];
	[p_messenger_yim release]; p_messenger_yim = [[_data objectForKey: OPUserProp_MessengerYIM] retain];
	[p_messenger_icq release]; p_messenger_icq = [[_data objectForKey: OPUserProp_MessengerICQ] retain];
	
	[p_website release]; p_website = [[_data objectForKey: OPUserProp_Website] retain];
	[p_lang release]; p_lang = [[_data objectForKey: OPUserProp_Lang] retain];
	[p_userType release]; p_userType = [[_data objectForKey: OPUserProp_UserType] retain];
	[p_userRank release]; p_userRank = [[_data objectForKey: OPUserProp_Rank] retain];
}

- (int) sendEmailWithSubject:(NSString *) _subj andText:(NSString *) _text {
	NSArray *_params = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt: p_userid],_subj,_text,@"",nil];
	XMLRPCResponse *sendMail = [[_delegateBoard _executeRequestMethodNamed: @"user.sendEmailToUser" 
																		   withParams: _params
																	   attachAuthData: NO] retain];
	
	
	BOOL resultOK = ![sendMail isFault];
	if (resultOK)
		return [[sendMail responseObject] intValue];
	
	[_params release];
	[sendMail release];
	return OFAPI_SENDMAIL_ERR;
}

- (BOOL) sendPrivateMessageWithSubject:(NSString *) _subj andText:(NSString *) _text {
	return [_delegateBoard.obj_authUser.user_personalBox sendNewPrivateMessageTo: self withSubject: _subj text:_text options:nil];
}

@end
